package com.augurit.gzcgwsp.ljzyz.web;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jbpm.api.ProcessEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.ljzyz.entity.YwYnLjzyzSqb;
import com.augurit.gzcgwsp.ljzyz.service.IYwYnBusinfoService;
import com.augurit.gzcgwsp.ljzyz.service.IYwYnLjzyzNsxzService;
import com.augurit.gzcgwsp.ljzyz.web.form.YwYnBusinfoForm;
import com.augurit.gzcgwsp.ljzyz.web.form.YwYnLjzyzSqbForm;
import com.augurit.gzcgwsp.printDoc.service.IYwPrintDocService;
import com.augurit.gzcgwsp.printDoc.web.form.YwPrintDocForm;
import com.augurit.gzcgwsp.sendNotice.entity.YwPublicOpinions;
import com.augurit.gzcgwsp.sendNotice.service.IYwPublicOpinionsService;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.wfex.common.util.WfUtilsEX;
import com.augurit.gzcgwsp.ywcmn.service.IYwComQyxxService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComQyxxForm;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.bi.web.form.WfBusTemplateForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.service.IWfBusClientService;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfBusClientAction;

@SuppressWarnings("serial")
@Results({
	@Result(name = CrudActionSupport.RELOAD, location = "yw-yn-ljzyz-nsxz.action", type = "redirect"),
	@Result(name = CrudActionSupport.SUCCESS, location = "/gzcgwsp/ljzyz/YwYnLjzyzNsxz/YwYnLjzyzNsxz.jsp"),
	@Result(name = CrudActionSupport.INPUT, location = "/gzcgwsp/ljzyz/YwYnLjzyzNsxz/YwYnLjzyzNsxz-input.jsp"),
	@Result(name = WfConstant.PRINT, location = WfConstant.PRINT_JSP),
	@Result(name = WfConstant.PRINT_DIR, location = WfConstant.PRINT_DIR_JSP)
})
public class YwYnLjzyzNsxzAction extends WfBusClientAction<YwYnLjzyzSqbForm>{

    @Autowired
    private IWfServiceEX wfServiceEX;
	@Autowired
	private IYwYnLjzyzNsxzService ywYnLjzyzNsxzService;
	@Autowired
    private ProcessEngine processEngine;
	@Autowired
	private IYwComQyxxService qyxxService;
    @Autowired
    private ISysCodeService syscodeService;
    @Autowired
    private IYwPrintDocService ywPrintDocService;
    @Autowired
	private IYwPublicOpinionsService ywPublicOpinionsService;
    @Autowired
    private IWfBusTemplateService wfBusTemplateService;
    @Autowired
	private IYwYnBusinfoService ywYnBusinfoService;
    
	private YwYnLjzyzSqbForm form;
	private Long id;
	private Long[] checkedIds;
	private Page<YwYnLjzyzSqbForm> page = new Page<YwYnLjzyzSqbForm>(10);
    /**
     * 保存业务并关联流程实例
     */
	@Override
	public String wfBusSave(){
		try{
        if (form.getQyid() == null) {
            YwComQyxxForm qyxxForm = qyxxService.getFormBySqdw(form.getSqdw(),form.getTemplateCode());
            if (qyxxForm != null) {
                WfUtils.renderWfFailtureJson("该企业名称已经存在，请点击选择企业从企业列表中选择该企业！");
                return null;
            }
        }
        String isYsl = super.getParameter("isYsl");
        WfBusInstanceTaskForm task = this.wfBusSave((IWfBusClientService)ywYnLjzyzNsxzService, form, YwYnLjzyzSqb.class.getSimpleName());
        
        if (form.getDfsj() == null) {
            String durationExpression = wfServiceEX.getProcDueExpressIonByTaskInstDbid(task.getTaskInstDbid());
            Date dfsj = wfServiceEX.calculateDueDate(form.getSarq(), durationExpression);
            form.setDfsj(dfsj);
            this.save();
        }
        if (StringUtils.isNotBlank(isYsl) && "1".equals(isYsl)) {
            String executionId =  processEngine.getHistoryService().createHistoryTaskQuery().taskId(task.getTaskInstDbid().toString()).uniqueResult().getExecutionId();
            processEngine.getExecutionService().jumpToActivity(executionId, "cksa");
            ywYnLjzyzNsxzService.changeYslState(form.getId(), null);
        }
        WfUtils.renderWfBusSaveJson(task, form);
		}catch (Exception e) {
			WfUtils.renderWfFailtureJson("请检查输入内容长度是否过大!");
		}
        return null;
	}
	
	@Override
	public String list() throws Exception {
		ywYnLjzyzNsxzService.search(page, form);
		return SUCCESS;
	}

	/**
	 * �������޸�
	 */
	@Override
	public String input() throws Exception {
	       this.initWfOpinions();
	        getRequest().setAttribute("CurrUserName", this.getLoginUser().getUser().getUserName());
	        Page<YwYnBusinfoForm> ywYnBusinfoFormPage = new Page<YwYnBusinfoForm>(10000);
	        List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
	        if(form.getQyid() != null){
	        	filters.add(new PropertyFilter("EQS_spsx","nsxz"));
	        	filters.add(new PropertyFilter("EQL_qyid",form.getQyid().toString()));
	        	ywYnBusinfoService.search(ywYnBusinfoFormPage, filters);
		        List<YwYnBusinfoForm> ywYnBusinfoFormList = ywYnBusinfoFormPage.getResult();
		        if(ywYnBusinfoFormList.size()>0){
		        	for(int i = 0;i<ywYnBusinfoFormList.size();i++){
		        		YwYnBusinfoForm ywYnBusinfoForm = ywYnBusinfoFormList.get(i);
		        		ywYnBusinfoForm.setDjrqStr(DateUtilsEX.dateTimeToString(ywYnBusinfoForm.getDjrq(),"yyyy-MM-dd"));
		        		ywYnBusinfoForm.setZyzyxqStr(DateUtilsEX.dateTimeToString(ywYnBusinfoForm.getZyzyxq(),"yyyy-MM-dd"));
		        	}	        	
		        }
	        }	        
	        List<SysCodeForm> sqdwlx = syscodeService.getItems("YW_SQDW_LX");
	        List<SysCodeForm> ywHbbm = syscodeService.getItems("ALL_HBBM");
	        getRequest().setAttribute("ywhbbm", ywHbbm);
	        getRequest().setAttribute("sqdwlx", sqdwlx);
	        getRequest().setAttribute("ywYnBusinfoFormPage", ywYnBusinfoFormPage);
			return INPUT;
	}

	/**
	 * �������������޸ĵ�Form����
	 */
	@Override
	public String save() throws Exception {
		ywYnLjzyzNsxzService.save(form);
		return RELOAD;
	}

	/**
	 * ɾ��һ����¼
	 */
	@Override
	public String delete() throws Exception {
		ywYnLjzyzNsxzService.delete(id);
		return RELOAD;
	}
	
	/**
	 * ɾ�������¼
	 */
	@Override
	public String deleteMore() throws Exception{
		ywYnLjzyzNsxzService.delete(checkedIds);
		return RELOAD;
	}
	
	/**
     * 出证
     */
    public String printcz() throws Exception {
        if(form.getId() != null && form.getId() > 0){
            List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(), form.getFileCode(), form.getId());
            if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
                return WfConstant.PRINT_DIR;
            }
        }
        return WfUtilsEX.wfBusPrint(form);
    }
	
    /**
     * 保存车辆检查表的信息
     * @return
     * @throws IOException 
     */
    public String saveCarCheckInfo() throws IOException{
    	String checkCarDate=getRequest().getParameter("checkDate");
        String checkCarPerson=getRequest().getParameter("checkPerson");
        String checkCarLeader=getRequest().getParameter("checkLeader");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date checkDate;
		try {
			if(StringUtils.isNotBlank(checkCarDate)){
				checkDate = sdf.parse(checkCarDate);
				form.setCheckCarDate(checkDate);
			}
			form.setCheckCarLeader(checkCarLeader);
	        form.setCheckCarPerson(checkCarPerson);
	        ywYnLjzyzNsxzService.updateForm(form);
	        getResponse().getWriter().print("success");
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    
	/**
	 * ׼��ҳ��ģ��
	 */
	@Override
	protected void prepareModel() throws Exception {
	    String id = super.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			form = ywYnLjzyzNsxzService.get(Long.parseLong(id));
		} else {
			form = new YwYnLjzyzSqbForm();
		}
		
		if (StringUtils.isNotBlank(form.getAcceptNo())) {
			Page<YwPublicOpinions> publicOpinionsPage = new Page<YwPublicOpinions>(10);//获取十条案件公示意见
			Page<YwPublicOpinions> page2 = ywPublicOpinionsService.getByAcceptNo(publicOpinionsPage,form.getAcceptNo());
	        super.getRequest().setAttribute("page2", page2);
        }		

        if (StringUtils.isBlank(form.getAcceptNo())) {
        	String rq = DateUtilsEX.getYearAndMonthAndDay();
        	form.setAcceptNo("gz26"+rq+"XXXXX");
        }
        if (StringUtils.isBlank(form.getSjr())) {
            form.setSjr(this.getLoginUser().getUser().getUserName());
        }
        if (form.getLarq() == null) {
        	form.setLarq(new Date());
        }
        
        if (StringUtils.isBlank(form.getCbyw())) {
            WfBusTemplateForm wfBusTemplateForm = wfBusTemplateService.getByTemplateCode(getTemplateCode());
            if (wfBusTemplateForm != null) {
                form.setCbyw(wfBusTemplateForm.getTemplateName());
            }
        }

        if (StringUtils.isBlank(form.getCbbm())) {
            form.setCbbm("余泥处");
        }
        
        if (form.getSqrq() == null) {
            form.setSqrq(new Date());
        }
        if (form.getSarq() == null) {
            form.setSarq(new Date());
        }
        if (form.getCpsj() == null) {
            form.setCpsj(new Date());
        }
        
        Locale locale = Locale.getDefault(); 
    	ResourceBundle localResource = ResourceBundle.getBundle("interfaceExchange", locale); 
    	String spdwdh = localResource.getString("spdwdh");//公示表中的审批单位  电话
    	super.getRequest().setAttribute("spdwdh", spdwdh);
//        if (form.getDfsj() == null) {
//            form.setDfsj(DateUtils.stringToDate(form.getCpsj().toString(), DateUtils.YEAR_MOUTH_DAY_));
//        }
	}
	

	public YwYnLjzyzSqbForm getModel() {
		return form;
	}
	
	// ����getter��setter����
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long[] getCheckedIds() {
		return checkedIds;
	}

	public void setCheckedIds(Long[] checkedIds) {
		this.checkedIds = checkedIds;
	}
	
	public Page<YwYnLjzyzSqbForm> getPage() {
		return page;
	}


	public void setPage(Page<YwYnLjzyzSqbForm> page) {
		this.page = page;
	}
}
